//
//  ContactPickerController.m
//  collection
//
//  Created by 张靖 on 7/8/12.
//  Copyright (c) 2012 Tsinghua University. All rights reserved.
//

#import "ContactPickerController.h"
#import "UserRelationCell.h"
#import "CollectionDataManager.h"
#import "pinyin.h"

@interface ContactPickerController ()

@property (retain, nonatomic) IBOutlet UITableView *contactTableView;
@property (nonatomic, retain) NSMutableArray* sections;

- (IBAction)onClickCancel:(id)sender;
- (BOOL)loadUserContacts;
- (BOOL)searchResult:(NSString *)contactName searchText:(NSString *)searchT;
- (void)sortUsers:(NSSet*)userSet;

@end

@implementation ContactPickerController

@synthesize delegate = _delegate;
@synthesize contactTableView = _contactTableView;
@synthesize sections = _sections;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    
    return self;
}

- (id)init {
    
    self = [self initWithNibName:@"ContactPickerController" bundle:nil];
    if (self) {
        
        NSMutableArray* sectionArray = [[NSMutableArray alloc] initWithCapacity:1];
        self.sections = sectionArray;
        [sectionArray release];
        for (int i = 0; i < 27; i++) 
        {
            NSMutableArray* subArray = [[NSMutableArray alloc] initWithCapacity:1];
            [self.sections addObject:subArray];
            [subArray release];
        }
    }
    
    return self;
}

- (void)dealloc {
    self.delegate = nil;
    self.sections = nil;
    [_contactTableView release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self loadUserContacts];
}

- (void)viewDidUnload
{
    [self setContactTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - [UITableViewDataSource]

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [[self.sections objectAtIndex:section] count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString* followeeCellID = @"UserRelationCellID";
    
    UserRelationCell* cell = (UserRelationCell*)[tableView dequeueReusableCellWithIdentifier:followeeCellID];
    if (cell == nil) {
        NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"UserRelationCell" owner:self options:nil];
        cell = [views objectAtIndex:0];
    }
    
    NSArray* subArray = [self.sections objectAtIndex:indexPath.section];
    UserInfo* oneUser = [subArray objectAtIndex:indexPath.row];
    cell.avatarImageView.image = oneUser.avatar;
    cell.nicknameLabel.text = oneUser.nickname;
    cell.signatureLabel.text = oneUser.signature;
    cell.actionButton.hidden = YES;
    
    return cell;
}

#pragma mark - [UITableViewDelegate]

- (float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([[self.sections objectAtIndex:section] count] > 0) 
    {
        return 23;
    }
    else 
    {
        return 0;
    }
}

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    // a - z
    if (section < 26) 
    {
        if ([[self.sections objectAtIndex:section] count] > 0) 
        {
            char c = (char)((int)'A' + section);
            return [NSString stringWithFormat:@"%c", c];
        }
    }
    else 
    {
        if ([[self.sections objectAtIndex:26] count] > 0) 
        {
            return @"#";
        }
    }
    
    return @"";
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    
    return cell.frame.size.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray* subArray = [self.sections objectAtIndex:indexPath.section];
    UserInfo* user = [subArray objectAtIndex:indexPath.row];
    
    if (self.delegate != nil) {
        [self.delegate contactPickerController:self userInfo:user];
    }
}

- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    NSMutableArray *indices = [NSMutableArray arrayWithCapacity:27];
    for (int i = 0; i < 27; i++)
    {
        if ([[self.sections objectAtIndex:i] count])
        {
            [indices addObject:[[ALPHA substringFromIndex:i] substringToIndex:1]];
        }
    }
    
    return indices;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    
    return [ALPHA rangeOfString:title].location;
}

#pragma mark - [Private methods]

- (IBAction)onClickCancel:(id)sender {
    
    [self dismissModalViewControllerAnimated:YES];
}

- (BOOL)loadUserContacts {
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    NSSet* userSet = sharedDataManager.cachedUsers;
    [self sortUsers:userSet];
    
    [self.contactTableView reloadData];
    
    return YES;
}

- (BOOL)searchResult:(NSString *)contactName searchText:(NSString *)searchT
{
	NSComparisonResult result = [contactName compare:searchT options:NSCaseInsensitiveSearch
											   range:NSMakeRange(0, searchT.length)];
	if (result == NSOrderedSame)
		return YES;
	else
		return NO;
}

- (void)sortUsers:(NSSet*)userSet
{
	for (NSMutableArray* subArray in self.sections) 
    {
        [subArray removeAllObjects];
    }
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    UserInfo* myself = sharedDataManager.currentLoginUser;
    
    NSString *sectionName = @"";
	for (UserInfo* user in userSet) 
	{
        if (user.userID == myself.userID) {
            continue;
        }
        
        // 处理多音字
        NSString* userName = user.nickname;
		if([self searchResult:userName searchText:@"曾"])
			sectionName = @"Z";
		else if([self searchResult:userName searchText:@"解"])
			sectionName = @"X";
		else if([self searchResult:userName searchText:@"仇"])
			sectionName = @"Q";
		else if([self searchResult:userName searchText:@"朴"])
			sectionName = @"P";
		else if([self searchResult:userName searchText:@"查"])
			sectionName = @"Z";
		else if([self searchResult:userName searchText:@"能"])
			sectionName = @"N";
		else if([self searchResult:userName searchText:@"乐"])
			sectionName = @"Y";
		else if([self searchResult:userName searchText:@"单"])
			sectionName = @"S";
		else
			sectionName = [[NSString stringWithFormat:@"%c",pinyinFirstLetter([userName characterAtIndex:0])] uppercaseString];
		
        NSUInteger firstLetter = [ALPHA rangeOfString:[sectionName substringToIndex:1]].location;
		
        if (firstLetter != NSNotFound) {
            [[self.sections objectAtIndex:firstLetter] addObject:user];   
        }
        else {
            [[self.sections objectAtIndex:26] addObject:user];   
        }
	}
}

@end
